package com.yishun.springboot.util;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

public class HttpUtile {

	public static String doGet(String url) throws IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();

		HttpGet request = new HttpGet(url);

		try (CloseableHttpResponse response = httpClient.execute(request)) {
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity);
		}
	}

	public static String doPost(String url, JSONObject params) throws IOException {
		return doPost(url, params, null);
	}

	public static String doPost(String url, JSONObject params, Map<String, Object> map) throws IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();

		HttpPost request = new HttpPost(url);
		Set<String> set = map.keySet();
		for (String li : set) {
			request.setHeader(li, map.get(li).toString());
		}

		StringEntity entity = new StringEntity(params.toString());
		entity.setContentType("application/json");
		request.setEntity(entity);

		try (CloseableHttpResponse response = httpClient.execute(request)) {
			HttpEntity responseEntity = response.getEntity();
			return EntityUtils.toString(responseEntity);
		}
	}
}
